/* test_threads_simple_1():
		A simple test that does:
			* Creates one additional thread (same prio as thread 0).
			* roughly verifies that they do RR.
			* At the end thread 0 does 'join' to thread 1.
*/


#include <assert.h>
#include <stdio.h>
#include <stdbool.h>
#include "test_general.h"

#include "user_threads.h"


bool test_threads_simple_1();

#define THREADS_NUM 2



static int thread1_start_routine(void * param) {
	if ( (*((int*)param)) != 53) {
		return -1;
	}

	some_long_operation(0.1);

	int i;
	for (i=0; i<5; i++) {
		some_long_operation(0.1);
		double now = get_precise_time();
		TEST_ASSERT(last_running_times[0] > now-0.08);
		TEST_ASSERT(last_running_times[1] > now-0.08);
	}

	some_long_operation(0.3);

	thread_ok[1] = true;
	return -63;
}


bool test_threads_simple_1()
{
	init_individual_test();

	int tmp;

/*	if (initilize_uthread_in_each_test) {
		tmp = uthread_init();
		TEST_ASSERT(tmp == UTHREAD_SUCCESS);
	} */

	uthread_id threads[THREADS_NUM];

	threads[0] = uthread_self();
	TEST_ASSERT(threads[0] == 0);

	int FiftyThree = 53;

	threads[1] = uthread_create(thread1_start_routine, &FiftyThree);
	/* TODO: make sure the prio of thread 0 is
		UTHREAD_MIN_PRIO */

	TEST_ASSERT(threads[1] == 1);

	some_long_operation(0.1);

	int i;
	for (i=0; i<5; i++) {
		some_long_operation(0.1);
		double now = get_precise_time();
		TEST_ASSERT(last_running_times[0] > now-0.08);
		TEST_ASSERT(last_running_times[1] > now-0.08);
	}

	some_long_operation(0.3);
	some_long_operation(0.5);

	double now = get_precise_time();
	TEST_ASSERT(last_running_times[0] > now-0.08);
	TEST_ASSERT(last_running_times[1] > now-0.85);
	TEST_ASSERT(last_running_times[1] < now-0.2);

	int tmp2;
	tmp = uthread_join(threads[1],&tmp2);
	TEST_ASSERT(UTHREAD_SUCCESS == tmp);
	TEST_ASSERT(-63 == tmp2);

	thread_ok[0] = true;

	TEST_ASSERT(are_all_threads_ok(THREADS_NUM));
	return true;
}
